package com.chongyahhh.security.security.configs.wechat;

import com.chongyahhh.security.security.common.CommonAuthentication;
import com.chongyahhh.security.security.common.CommonUser;
import com.chongyahhh.security.security.common.UserAuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * @Author chongyahhh
 * 微信认证服务支持
 */
@Component
public class WechatAuthenticationProvider implements AuthenticationProvider {

    private final UserAuthenticationService userAuthenticationService;

    private final String OPEN_ID = "openId";

    @Autowired
    public WechatAuthenticationProvider(UserAuthenticationService userAuthenticationService) {
        this.userAuthenticationService = userAuthenticationService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 先转换为我们的 Authentication
        CommonAuthentication auth = (CommonAuthentication) authentication;
        // 获取 openId
        String openId = (String)auth.getExtra(OPEN_ID);

        CommonUser user = (CommonUser)userAuthenticationService.loadUserUnderWechat(openId);

        WechatAuthentication wechatAuthentication = new WechatAuthentication(user.getUsername(), user.getPassword(), user.getUserId(), user.getAuthorities());
        wechatAuthentication.setExtra(OPEN_ID, openId);

        return wechatAuthentication;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        // 该 Provider 支持验证 WechatAuthentication
        return WechatAuthentication.class.isAssignableFrom(aClass);
    }
}
